package com.hmall.common.interceptor;

import com.hmall.common.utils.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //从请求里获取请求头user-info的值：用户id
        String userId = request.getHeader("user-info");
        //如果值非空，就将用户id绑定到当前线程上
        if (StringUtils.hasText(userId)) {
            UserContext.setUser(Long.parseLong(userId));
        }
        //直接放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //一次请求结束后，将当前线程上绑定的数据清理掉
        UserContext.removeUser();
    }
}
